<?php

namespace app\api\model;

use think\Db;

class Topup extends Common
{
    static public function index($user_id, $price, $money, $method, $sid=0, $coupon_id=0)
    {
        $order_sn = uniqid() . mt_rand(10000,99999);

        // 新增优惠券逻辑，直接核销优惠券，若未支付则在api/timing中返还优惠券
        if ($coupon_id) {
            $coupon = Db::name('user_coupon')->where(['state' => 0, 'user_id' => $user_id, 'id'=> $coupon_id, 'address_id' => 0])->find();
            if ($coupon) {
                if ($coupon['minprice'] < $price && $coupon['price'] > 0 && $coupon['price'] <= $price) {
                    $price = $price - $coupon['price'];
                    Db::name('user_coupon')->where(['id'=>$coupon_id])->update(['update_time'=>time(), 'state'=>1, 'data' => $order_sn]);
                }
            }
        }

        $data = [
            "sid" => $sid,
            "fk_userid" => $user_id,
            "price" => $price,
            "money" => $money,
            "type" => $method,
            "numbers" => $order_sn,
        ];

        $order = self::create($data);

        return ['id' => $order->id, 'order_sn' => $order_sn, 'price' => $price];
    }
}
